<template>
  <div class="tmpl">
    <h1>登录表单</h1>
    <el-form :model="loginForm" ref="loginForm" :rules="loginRules" label-width="100px" style="width:500px" status-icon >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input placeholder="请输入密码" v-model="loginForm.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model.number="loginForm.code" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="submitForm('loginForm')">提 交</el-button>
        <el-button type="danger" @click="resetForm('loginForm')">重 置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Demo',
  data () {
    var checkIsNull = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('字段不得为空'))
      } else {
        callback()
      }
    }
    var checkIsNum = (rule, value, callback) => {
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          return callback(new Error('必须为数字'))
        } else {
          callback()
        }
      }, 800)
    }
    return {
      loginForm: {
        username: '',
        password: '',
        code: ''
      },
      loginRules: {
        username: [{ validator: checkIsNull, trigger: 'blur' }],
        password: [{ validator: checkIsNull, trigger: 'blur' }],
        code: [{ validator: checkIsNull, trigger: 'blur' }, { validator: checkIsNum, trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let username = this.loginForm.username
          let password = this.loginForm.password
          let code = this.loginForm.code
          this.$message({
            showClose: true,
            message: `用户名：${username}, 密码：${password}, 验证码：${code}`,
            type: 'success'
          })
        } else {
          this.$message({
            showClose: true,
            message: '不允许登录！',
            type: 'error'
          })
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
h1 {
  font-weight: normal;
}
</style>
